package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * @Author 作者：小龙猿
 * @Project 项目：seata-at
 * @Time 时间：2021/9/22 11:47
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;

    @GlobalTransactional //开启全局事务，只在第一个模块添加
    @Transactional //控制本地事务
    @Override
    public void create(Order order) {
        //远程调用发号器，获取订单id
        Long orderId = Long.valueOf(easyIdClient.nextId("order_business"));
        //Long orderId = new Random().nextLong();
        order.setId(orderId);
        orderMapper.create(order);
        //远程调用库存，减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //远程调用账户，扣减账户金额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
